package com.vogue.supplymall.account.shiro.session;

import java.io.Serializable;
import java.util.Collection;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import com.vogue.gear.memory.provider.IMemProvider;
import com.vogue.gear.memory.provider.impl.MemProviderAdapter;

public class MallSessionDao extends EnterpriseCacheSessionDAO {
	
    private IMemProvider<Session> accountmem;
    
	public MallSessionDao(IMemProvider<Session> memProvider){
		super();
		this.accountmem=memProvider;
//		Collection<Session> coll = getActiveSessions();
//		for(Session ses : coll) {
//			accountmem.remove((String)ses.getId());
//		}
	}

	@Override
	protected void doUpdate(Session session) {
		// TODO Auto-generated method stub
		String sid=(String)session.getId();
		accountmem.put(sid, session);
	}

	@Override
	protected void doDelete(Session session) {
		// TODO Auto-generated method stub
		String sid=(String)session.getId();
		accountmem.remove(sid);
	}
	
	@Override
	public Collection<Session> getActiveSessions() {
		// TODO Auto-generated method stub
		return accountmem.getAll();
	}

	@Override
	protected Serializable doCreate(Session session) {
		// TODO Auto-generated method stub
		String sid = (String)this.generateSessionId(session);  
        this.assignSessionId(session, sid);  
        accountmem.put(sid, session);
		cache(session, sid);
        return sid;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		// TODO Auto-generated method stub
		Session ses=accountmem.get((String)sessionId);
		return ses;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Session readSession(Serializable sessionId) throws UnknownSessionException {
//        Session s = getCachedSession(sessionId);
//        if (s == null) {
//            s = super.readSession(sessionId);
//            if(s!=null){
//            	cache(s, sessionId);
//            }
//        }
		Session s=doReadSession(sessionId);
        //如果主缓存从失效中恢复就将本地缓存的session同步到主缓存
        if(s!=null && accountmem instanceof MemProviderAdapter && ((MemProviderAdapter)accountmem).getMainstatus()=='R'){
        	accountmem.put((String)sessionId, s);
        	((MemProviderAdapter)accountmem).setMainstatus('T');
        }
        return s;
    }

}
